let express = require('express');
let mysql = require('mysql');
let bodyParser = require('body-parser');
const cors = require('cors');
let session = require('express-session');
let multer = require('multer');
let path = require('path');

let app = express();
app.use(cors());

// 设置文件存储引擎
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, '../login/img/');
    },
    filename: function(req, file, cb) {
        cb(null, Date.now() + path.extname(file.originalname)); // 重命名文件以避免冲突
    }
});

const upload = multer({ storage: storage });

// 数据库连接
let db = mysql.createConnection({
    host: 'localhost', // 数据库地址
    user: 'root', // 数据库用户名
    password: '0526', // 数据库密码
    database: 'blog' // 选择的数据库名称
});

db.connect((err) => {
    if (err) throw err;
    console.log('数据库连接成功~~~');
});

// 解析请求体数据
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 开启session中间件
app.use(session({
    secret: 'secret',
    resave: false,
    saveUninitialized: true
}));

// 添加用户路由
app.post('/addUser', (req, res) => {
    let { username, email, password, role, status } = req.body;
    console.log(username, email, password, role, status);

    if (!username || !email || !password || !role || !status) {
        return res.send({ success: false, message: '参数不完整' });
    }

    let query = 'INSERT INTO users (username, email, password, role, status) VALUES (?, ?, ?, ?, ?)';
    db.query(query, [username, email, password, role, status], (err, result) => {
        if (err) {
            console.error('插入错误：', err);
            res.json({ success: false, message: '插入失败' });
        } else {
            console.log('插入成功：', result);
            res.json({ success: true, message: '插入成功' });
        }
    });
});

// 查询用户数据路由
app.get('/users', (req, res) => {
    let query = 'SELECT * FROM users';
    db.query(query, (err, results) => {
        if (err) {
            console.error('查询错误：', err);
            res.json({ success: false, message: '查询失败' });
        } else {
            res.json({ success: true, data: results });
        }
    });
});

// 删除用户路由
app.delete('/deleteUser/:id', (req, res) => {
    const userId = req.params.id;

    if (!userId) {
        return res.send({ success: false, message: '参数不完整' });
    }

    let query = 'DELETE FROM users WHERE id = ?';
    db.query(query, [userId], (err, result) => {
        if (err) {
            console.error('删除错误：', err);
            res.json({ success: false, message: '删除失败' });
        } else {
            console.log('删除成功：', result);
            res.json({ success: true, message: '删除成功' });
        }
    });
});

// 删除文章路由
app.delete('/deleteArticle/:id', (req, res) => {
    const articleId = req.params.id;

    if (!articleId) {
        return res.send({ success: false, message: '参数不完整' });
    }

    let query = 'DELETE FROM articles WHERE id = ?';
    db.query(query, [articleId], (err, result) => {
        if (err) {
            console.error('删除错误：', err);
            res.json({ success: false, message: '删除失败' });
        } else {
            console.log('删除成功：', result);
            res.json({ success: true, message: '删除成功' });
        }
    });
});

// 更新用户路由
app.put('/updateUser/:id', (req, res) => {
    const userId = req.params.id;
    let { username, email, password, role, status } = req.body;

    if (!username || !email || !password || !role || !status) {
        return res.send({ success: false, message: '参数不完整' });
    }

    let query = 'UPDATE users SET username = ?, email = ?, password = ?, role = ?, status = ? WHERE id = ?';
    db.query(query, [username, email, password, role, status, userId], (err, result) => {
        if (err) {
            console.error('更新错误：', err);
            res.json({ success: false, message: '更新失败' });
        } else {
            console.log('更新成功：', result);
            res.json({ success: true, message: '更新成功' });
        }
    });
});

// 添加文章路由
app.post('/addArticle', upload.single('category'), (req, res) => {
    let { title, author, status, content } = req.body;
    let categoryPath = req.file.path; // 图片路径

    if (!title || !author || !status || !categoryPath || !content) {
        return res.send({ success: false, message: '参数不完整' });
    }

    let query = 'INSERT INTO articles (title, author, status, category, content) VALUES (?, ?, ?, ?, ?)';
    db.query(query, [title, author, status, categoryPath, content], (err, result) => {
        if (err) {
            console.error('插入错误：', err);
            res.json({ success: false, message: '插入失败' });
        } else {
            console.log('插入成功：', result);
            res.json({ success: true, message: '插入成功' });
        }
    });
});

// 查询文章数据路由
app.get('/articles', (req, res) => {
    let query = 'SELECT * FROM articles';
    db.query(query, (err, results) => {
        if (err) {
            console.error('查询错误：', err);
            res.json({ success: false, message: '查询失败' });
        } else {
            res.json({ success: true, data: results });
        }
    });
});

// 更新文章路由
app.put('/updateArticle/:id', upload.single('category'), (req, res) => {
    const articleId = req.params.id;
    let { title, author, status, content } = req.body;
    let categoryPath = req.file ? req.file.path : null; // 图片路径，如果未上传新图片则保持原路径

    if (!title || !author || !status || !content) {
        return res.send({ success: false, message: '参数不完整' });
    }

    let query = 'UPDATE articles SET title = ?, author = ?, status = ?, category = ?, content = ? WHERE id = ?';
    db.query(query, [title, author, status, categoryPath, content, articleId], (err, result) => {
        if (err) {
            console.error('更新错误：', err);
            res.json({ success: false, message: '更新失败' });
        } else {
            console.log('更新成功：', result);
            res.json({ success: true, message: '更新成功' });
        }
    });
});

app.listen(8080, () => {
    console.log('服务器启动成功~~~');
});